/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ca.ubc.icapture.genapha.actions;

/**
 *
 * @author btripp
 */
import ca.ubc.icapture.genapha.beans.Login;
import ca.ubc.icapture.genapha.forms.AllListForm;
import ca.ubc.icapture.genapha.forms.SnpGeneForm;
import icapture.beans.DB.Gene;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * @version 	1.0
 * @author
 */
public class PathwayGeneExportAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        //Now set and send the output.
        response.reset();
        String filename = "";
        String delimiter = "";
        response.addHeader("cache-control", "must-revalidate");
        response.setHeader("Content-type", "application/xls");
        SnpGeneForm sgForm = (SnpGeneForm) form;
        delimiter = sgForm.getDlimiter();
        filename = sgForm.getFilename();
        HashMap<String, ArrayList<Gene>> snpGeneHash = sgForm.getPathGeneHash();
        PrintWriter pw = response.getWriter();
        if (delimiter.equals("tab")) {
            delimiter = "\t";
            response.setHeader("Content-disposition", "attachment; filename=" + filename + ".txt");
            formatOutput(delimiter, pw, snpGeneHash);
        } else if (delimiter.equals("csv")) {
            delimiter = ",";
            response.setHeader("Content-disposition", "attachment; filename=" + filename + ".csv");
            formatOutput(delimiter, pw, snpGeneHash);
        }
        //Now output the results and return null;
        response.flushBuffer();
        return null;
    }

    private void formatOutput(String delimiter, PrintWriter pw, HashMap<String, ArrayList<Gene>> snpGeneHash) {
        String excelOutput = "";
        String header = "Pathway Name" + delimiter + "NCBI Gene IDs" + delimiter + "Gene Name" + "\r\n";
        pw.print(header);
        Set<String> keys = snpGeneHash.keySet();
        //itr is pathway name
        for (String itr : keys) {
            ArrayList<Gene> tmpGeneList = snpGeneHash.get(itr);
            for (Gene tmpGene : tmpGeneList){
                excelOutput += itr + delimiter + tmpGene.getEntrezGeneID() + delimiter + tmpGene.getName() + "\r\n";
                //print
                pw.print(excelOutput);
                //clear
                excelOutput = "";
            }
        }
        pw.checkError();
    }
}
